<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH.'libraries/Facebook/facebook.php';

class Welcome extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
            $all_userdata = $this->session->all_userdata();
            // if user already have result of gift, redirect gift tree page
            if( isset($all_userdata['session_id']) && isset($all_userdata['login_success']) && isset($all_userdata['usercode_id']) && isset($all_userdata['lucky_gift_type']) ) {
                redirect('gift-tree', 'location');
            }
            
            $data['site_url'] = site_url();
            $this->load->view('header');
            $this->load->view('welcome_message', $data);
            $this->load->view('footer');
	}
        
        public function checkcode()
        {                      
            // dont have POST[code] redirect to first page
            if(!isset($_POST) || !isset($_POST['code']))
                redirect('/welcome', 'location');
            else {                
                $data = array();
                $code = mysql_real_escape_string(trim($_POST['code']));         
                if(strlen($code)==9) {                    
                    // check code valid
                    $query = $this->db->query("SELECT id, used FROM users_code WHERE usercode = '$code' AND status = 1");
                    // if valid
                    if($query->num_rows() > 0) {
                        // get past used
                        $result_array = $query->result_array();                        
                        // check count > 3, show popup over times play, denied play
                        if($result_array[0]['used']>2) {
                            $data['overplay'] = 1;
                        }
                        // redirect to share FB when user play > 1 times
                        else if($result_array[0]['used']>0) {
                            // set default session data
                            $this->session->set_userdata('login_success',1);
                            $this->session->set_userdata('usercode_id', $result_array[0]['id']);
                            $this->session->set_userdata('usercode', $code);
                            $this->session->set_userdata('used', $result_array[0]['used']);
                            // set user-info to session
                            $query_user = $this->db->query("SELECT * FROM users WHERE usercode_id = ".$result_array[0]['id']." LIMIT 1");
                            $user = $query_user->row_array();
                            $this->session->set_userdata('user_info', array('users_id' => $user['id'], 'name' => $user['name'], 'address' => $user['address'], 'idcard' => $user['idcard'], 'phone' => $user['phone'], 'email' => $user['email']));
                            //print_r($this->session->all_userdata()); die();
                            // post link FB
                            $this->postfb();
                            // check post link FB success
                            $all_userdata = $this->session->all_userdata();                            
                            if(isset($all_userdata['fb_link_id'])) {
                                $data['success_link'] = base_url()."gift-tree";
                            }
                            else {
                                $data['success_link'] = base_url()."complete";
                            }
                        }
                        // access normal first time
                        else {
                            // create session data
                            $this->session->set_userdata('login_success',1);
                            $this->session->set_userdata('usercode_id', $result_array[0]['id']);
                            $this->session->set_userdata('usercode', $code);
                            $this->session->set_userdata('used', $result_array[0]['used']);
                            // create gift link
                            $data['success_link'] = base_url()."gift-tree";
                        }                        
                    }
                }
            }           
            //$data['userdata'] = $this->session->userdata;
            $this->session->set_userdata('sendmail', 0);
            $this->load->view('checkcode', $data);            
        }
        
        public function gifttree()
        {
            $all_userdata = $this->session->all_userdata();
            //print_r($all_userdata); die();
            // dont have session security, redirect to first page
            if( !isset($all_userdata['session_id']) || !isset($all_userdata['login_success']) || !isset($all_userdata['usercode_id']) ) {
                redirect('/welcome', 'location');
            }          
            // if user already pick gift
            $data = array();
            if(isset($all_userdata['lucky_gift_type'])) {
                $json = json_decode($this->load->view('gift', $all_userdata, true));
                $data['already_have_gift_html'] = $json->html;
            }
            $this->load->view('header');
            $this->load->view('gifttree', $data);
            $this->load->view('footer');
        }
        
        public function goodluck()
        {                 
            $all_userdata = $this->session->all_userdata();
            // dont have session security, redirect to first page
            if( !isset($all_userdata['session_id']) || !isset($all_userdata['login_success']) || !isset($all_userdata['usercode_id']) ) {
                redirect('/welcome', 'location');
            }
            
            // deny cheating :)
            if(isset($all_userdata['lucky_gift_type'])) {
                redirect('/gift-tree', 'location');
            }
           
            // check over times play TODO
            
            // check gift rule time; 1 week: days <= 6
            $now = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $start_date = START_DATE;
            
            $diff = abs($now - $start_date);           
            
            $years = floor($diff / (365*60*60*24));
            $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
            $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
            
            // current week
            if( in_array($days,array(0,1,2,3,4,5,6)) ) {
                $week = 1;
            }
            else if( in_array($days,array(7,8,9,10,11,12,13)) ){
                $week = 2;
            }
            else if( in_array($days,array(14,15,16,17,18,19,20)) ){
                $week = 3;
            }
            else
                $week = 4;
            
            //echo "count days: $days current week ".$week.'<br>';            
            // end campaigns
            if($week > 3) {
                // STOP campaigns
                redirect('/welcome', 'location');
            }            
            // count gift was taken
            $ao_taken = $so_taken = $wish_taken = 0;            
            $query = $this->db->query("SELECT COUNT(gift) as taken,gift FROM users_gift GROUP BY gift");                        
            
            foreach($query->result_array() as $gift) {
                if($gift['gift'] == 'ao')
                    $ao_taken = $gift['taken'];
                if($gift['gift'] == 'so')
                    $so_taken = $gift['taken'];
                if($gift['gift'] == 'wish')
                    $wish_taken = $gift['taken'];
            }            
            //echo $wish_taken.'-'.TOTAL_WEEK_WISH.'-'.GIFT_IN_WEEK__WISH; 
            
            // gift exists in current week
            $current_week_gift = array();
            $array_gift_lucky = array();
            $curren_week_gift['ao'] = (TOTAL_WEEK * GIFT_IN_WEEK__AO) - ((TOTAL_WEEK - $week)*GIFT_IN_WEEK__AO) - $ao_taken;
            $curren_week_gift['so'] = (TOTAL_WEEK * GIFT_IN_WEEK__SO) - ((TOTAL_WEEK - $week)*GIFT_IN_WEEK__SO) - $so_taken;
            //$curren_week_gift['wish'] = (TOTAL_WEEK_WISH * GIFT_IN_WEEK__WISH) - ((TOTAL_WEEK_WISH - $week)*GIFT_IN_WEEK__WISH) - $wish_taken;
            $curren_week_gift['wish'] = 1 - $wish_taken;
            // ao exists
            if($curren_week_gift['ao'] > 0) {
                $array_gift_lucky[] = "ao";
            }
            // so exists
            if($curren_week_gift['so'] > 0) {
                $array_gift_lucky[] = "so";
            }
            // wish exists
            if($curren_week_gift['wish'] > 0) {
                $array_gift_lucky[] = "wish";
            }
            
            //print_r($curren_week_gift); print_r($array_gift_lucky); echo '<br>'; die();
            
            $result = array();
            // if exists gift in current week, user can try :P
            if(count($array_gift_lucky) > 0) {                
                // lucky or no :D
                $rand = rand(0,LUCKY_DIFFICULT);
                $lucky = rand(0,LUCKY_DIFFICULT);
                // congratulation!
                if($rand == $lucky) {             
                    $type_gift = rand(0, count($array_gift_lucky)-1);
                    $luck_gift = $array_gift_lucky[rand(0, $type_gift)];
                    // write lucky gift into session
                    $this->session->set_userdata('lucky_gift_type', $luck_gift);
                    // result return via ajax
                    $result['lucky_gift_type'] = $luck_gift;
                }
                // unlucky
                else {
                    // generate fonepad code
                    $fonepad_code = $this->generateRandomString(9);
                    $this->session->set_userdata('lucky_gift_type', 'code');
                    $this->session->set_userdata('fonepad_code', $fonepad_code);
                    // result return via ajax
                    $result['lucky_gift_type'] = "code";
                    $result['fonepad_code'] = $fonepad_code;
                }
            }
            // empty gift in current week, user get fonepad code
            else {
                // generate fonepad code
                $fonepad_code = $this->generateRandomString(9);
                $this->session->set_userdata('lucky_gift_type', 'code');
                $this->session->set_userdata('fonepad_code', $fonepad_code);
                // result return via ajax
                $result['lucky_gift_type'] = "code";
                $result['fonepad_code'] = $fonepad_code;
            }
            // load view
            $this->load->view('gift', $result);             
        }
        
        public function info()
        {
            $all_userdata = $this->session->all_userdata(); //print_r($all_userdata); die();
            
            // dont have session security, redirect to first page
            if( !isset($all_userdata['session_id']) || !isset($all_userdata['login_success']) || !isset($all_userdata['usercode_id']) ) {        
                redirect('/welcome', 'location');
            }             

            // user not yet saving info
            if( !isset($all_userdata['user_info']) ) {
                // check over times play TODO
                // not yet choice gift            
                if(!isset($all_userdata['lucky_gift_type'])) {
                    redirect('/gift-tree', 'location');
                }            
                else {
                    // process submit
                    if(isset($_POST['submit'])) { 
                        // validate TODO
                        $err = array();                    
                        $arr_validate = array('fname/họ tên' => 'text', 'address/địa chỉ' => 'text', 'idcard/cmnd' => 'idcard', 'email/email' => 'email', 'phone/số điện thoại' => 'phone');
                        foreach($arr_validate as $field_name => $field_type) {
                            $field_name = explode('/', $field_name);
                            $field_name_show = $field_name[1];
                            $field_name = $field_name[0];
                            // check exits
                            if(!isset($_POST[$field_name])) {
                                echo $field_name;
                                $err['error'] = true;
                                $err['error_msg'][$field_name] = 'Vui lòng nhập '.$field_name_show;
                            }
                            // check with type
                            if(!isset($err['error_msg'][$field_name])) {
                                // text
                                if($field_type == 'text') {
                                    if(trim($_POST[$field_name]) == "") {
                                        $err['error'] = true;
                                        $err['error_msg'][$field_name] = 'Vui lòng nhập '.$field_name_show;
                                    }
                                }
                                // idcard
                                else if($field_type == 'idcard') {
                                    if(!is_numeric($_POST[$field_name]) || strlen($_POST[$field_name])>12) {
                                        $err['error'] = true;
                                        $err['error_msg'][$field_name] = 'Vui lòng nhập '.$field_name_show. ' hợp lệ';
                                    }                                    
                                    // check id card exist
                                    $query_user = $this->db->query("SELECT id FROM users WHERE idcard = ".$_POST[$field_name]);
                                    if($query_user->num_rows()>0) {
                                        $err['error'] = true;
                                        $err['error_msg'][$field_name] = 'Số ' . $field_name_show. ' này đã tồn tại';
                                    }
                                }
                                // email
                                else if($field_type == 'email') {                                
                                    if(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $_POST[$field_name])){
                                        $err['error'] = true;
                                        $err['error_msg'][$field_name] = 'Vui lòng nhập địa chỉ '.$field_name_show. ' hợp lệ';
                                    }
                                    // check email exist
                                    $query_user = $this->db->query("SELECT id FROM users WHERE email = '".$_POST[$field_name]."'");
                                    if($query_user->num_rows()>0) {
                                        $err['error'] = true;
                                        $err['error_msg'][$field_name] = 'Địa chỉ ' . $field_name_show. ' này đã tồn tại';
                                    }
                                }
                                // phone
                                else if($field_type == 'phone') {
                                    if(!is_numeric($_POST[$field_name]) || strlen($_POST[$field_name])<8) {
                                        $err['error'] = true;
                                        $err['error_msg'][$field_name] = 'Vui lòng nhập '.$field_name_show. ' hợp lệ';
                                    }
                                    // check phone exist
                                    $query_user = $this->db->query("SELECT id FROM users WHERE phone = ".$_POST[$field_name]);
                                    if($query_user->num_rows()>0) {
                                        $err['error'] = true;
                                        $err['error_msg'][$field_name] = $field_name_show. ' này đã tồn tại';
                                    }
                                }
                            }   
                        }
                        // parse error
                        if( isset($err['error']) ) {
                            $err['post'] = $_POST;
                            $this->load->view('header');
                            $this->load->view('info',$err);
                            $this->load->view('footer');
                            return;
                        }
                        // resend success variable and show error
                        // clean variable for sql injection
                        $usercode_id = mysql_escape_string($all_userdata['usercode_id']);
                        $name = mysql_escape_string($_POST['fname']);
                        $address = mysql_escape_string($_POST['address']);
                        $idcard = mysql_escape_string($_POST['idcard']);
                        $email = mysql_escape_string($_POST['email']);
                        $phone = mysql_escape_string($_POST['phone']);
                        $createtime = mktime( date('H'), date('i'), date('s'), date('m'), date('d'), date('Y'));        
                        $ip = $this->session->userdata('ip_address');
                        $user_agent = mysql_escape_string($this->session->userdata('user_agent'));                        
                        // insert user info
                        $this->db->query("INSERT INTO users(usercode_id,name,address,idcard,email,phone,createtime,ip,user_agent) 
                        VALUES($usercode_id, '".$name."', '".$address."', '".$idcard."', '".$email."', '".$phone."', '".$createtime."', '".$ip."', '".$user_agent."')");
                        // insert user gift
                        $query_user = $this->db->query("SELECT id FROM users WHERE idcard = $idcard");
                        $user = $query_user->row_array();
                        $users_id = $user['id'];
                        $gift = $all_userdata['lucky_gift_type'];
                        $this->db->query("INSERT INTO users_gift(user_id,usercode_id,gift,createtime) VALUES($users_id, $usercode_id, '".$gift."', $createtime)");
                        // if gift is code, insert fonepad code
                        if($gift == 'code') {
                            $createtime = time();
                            $fonepad_code = $all_userdata['fonepad_code'];
                            $this->db->query("INSERT INTO fonepad_code(user_id,fonepadcode,createtime) VALUES($users_id, '".$fonepad_code."', $createtime)");
                        }                        
                        //update status code = 0
                        $this->db->query("UPDATE users_code SET status = 0, used = used+1 WHERE id = $usercode_id");
                        // redirect and show popup
                        $this->session->set_userdata('user_info', array('users_id' => $users_id, 'name' => $name, 'address' => $address, 'idcard' => $idcard, 'phone' => $phone, 'email' => $email));
                        $this->session->set_userdata('update_user_info', 1);
                        $this->sendmail();
                    }
                    // normal load
                    else {
                        $data['fname'] = '';  
                        $data['address'] = '';  
                        $data['idcard'] = '';  
                        $data['email'] = '';  
                        $data['phone'] = '';  
                    }
                }
            }
            // already user info (for case show success popup or playtime > 1)
            else {
                $data['user_info'] = "success";
                // send email to user for play > 1 times play
                if($all_userdata['used'] > 0 && $all_userdata['sendmail'] == 0) {
                    $this->sendmail();
                }
                // update playtime, new code if user have new data
                if(!isset($all_userdata['update_user_info'])) {
                    $usercode_id = mysql_escape_string($all_userdata['usercode_id']);
                    $idcard = mysql_escape_string($all_userdata['user_info']['idcard']);
                    // insert user gift
                    $query_user = $this->db->query("SELECT id FROM users WHERE idcard = $idcard");
                    $user = $query_user->row_array();
                    $users_id = $user['id'];
                    $gift = $all_userdata['lucky_gift_type'];
                    $this->db->query("INSERT INTO users_gift(user_id,usercode_id,gift) VALUES($users_id, $usercode_id, '".$gift."')");
                    // if gift is code, insert fonepad code
                    if($gift == 'code') {
                        $createtime = time();
                        $fonepad_code = $all_userdata['fonepad_code'];
                        $this->db->query("INSERT INTO fonepad_code(user_id,fonepadcode,createtime) VALUES($users_id, '".$fonepad_code."', $createtime)");
                    }                        
                    //update status code = 0
                    $this->db->query("UPDATE users_code SET status = 0, used = used+1 WHERE id = $usercode_id");
                    // set flag update new data success
                    $this->session->set_userdata('update_user_info', 1);
                }
            }
            
            $this->load->view('header');
            $this->load->view('info', $data);
            $this->load->view('footer');
        }
        
        public function sendmail()
        {
            $all_userdata = $this->session->all_userdata();
            
            // dont have session security, redirect to first page
            if( !isset($all_userdata['session_id']) || !isset($all_userdata['login_success']) || !isset($all_userdata['usercode_id']) ) {        
                redirect('/welcome', 'location');
            }
            // dont have user info, redirect to user info page
            else if(!isset($all_userdata['user_info'])) {
                redirect('/user-info', 'location');
            }
            // send email confirm
            // parse email template
            else {                
                $this->load->library('email');
                
                //prepare data
                $all_userdata['user_info']['name'] = str_replace(".", "", $all_userdata['user_info']['name']);
                $all_userdata['user_info']['address'] = str_replace(".", ". ", $all_userdata['user_info']['address']);

                $subject = 'ASUS Fonepad - Santa Claus Is Calling';                

                // Get full html:
                $hate = "'Roboto Condensed', Arial, sans-serif";
                $body =
                '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                <html xmlns="http://www.w3.org/1999/xhtml">
                <head>
                    <meta http-equiv="content-type" content="text/html" />
                    <meta name="author" content="THUYBUI" />
                    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                    <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,700,800" rel="stylesheet" type="text/css" />
                    <link href="http://fonts.googleapis.com/css?family=Roboto+Condensed:700,300&amp;subset=latin,vietnamese" rel="stylesheet" type="text/css" />
                    <title>'.htmlspecialchars($subject, ENT_QUOTES, $this->email->charset).'</title>
                </head>
                <style>
                    body{  }
                </style>
                <body>
                <div style="font-family: ' . $hate . '; width:650px; margin:0 auto;">
                    <table border="0" cellspacing="0" cellpadding="0" style="width:650px; background:#fff;">
                        <tr><td  style="margin:0; vertical-align:top;line-height:0;" colspan="3"><img src="'.base_url().'public/email/img/top.jpg"/></td></tr>
                        <tr>
                            <td style="margin:0; vertical-align:top; line-height:0; width:27px; height:288px; background:#bb0428;"><img src="'.base_url().'public/email/img/left.jpg"/></td>
                            <td style="margin:0; vertical-align:top; width:574px; height:288px; background:#bb0428; padding:0 10px; color:#fff; font-size:27px; background:#bb0428;">
                                <p style="margin:0; padding:0;">Chúc mừng bạn đã tham gia thành công trò chơi <span style="text-transform:uppercase; font-weight:bold;">Santa Claus Is Calling</span> của <strong>ASUS Fonepad</strong>. Đây là những thông tin bạn đã đăng ký với chương trình:</p>
                                <p style="padding:10px 0 0 0; margin:0;"><strong>Họ tên: </strong>'.$all_userdata['user_info']['name'].'</p>
                                <p style="padding:0; margin:0;"><strong>Địa chỉ:</strong> '.$all_userdata['user_info']['address'].'</p>
                                <p style="padding:0; margin:0;"><strong>CMND:</strong> '.$all_userdata['user_info']['idcard'].'</p>
                                <p style="padding:0; margin:0;"><strong>Điện thoại:</strong> '.$all_userdata['user_info']['phone'].'</p>
                                <p style="padding:0; margin:0;"><strong>Email:</strong> '.$all_userdata['user_info']['email'].'</p>
                            </td>
                            <td style="margin:0; vertical-align:top; line-height:0; width:27px; height:288px; background:#bb0428;"><img src="'.base_url().'public/email/img/right.jpg"/></td>
                        </tr>
                        <tr><td  style="margin:0; vertical-align:top;line-height:0;" colspan="3"><img src="'.base_url().'public/email/img/footer.jpg"/></td></tr>
                    </table>
                </div>
                </body>
                </html>';
                
                $result = $this->email
                    ->from('santaclausiscalling@gmail.com')
                    //->reply_to('yoursecondemail@somedomain.com')    // Optional, an account where a human being reads.
                    ->to($all_userdata['user_info']['email'])
                    ->subject($subject)
                    ->message($body)
                    ->send();
                $this->session->set_userdata('sendmail', 1);                
                redirect('/user-info?status=success', 'location');
//                var_dump($result);
//                echo '<br />';
//                echo $this->email->print_debugger();
//
//                exit;
//                
                // clear all session TODO
            }
            
        }
        
        public function complete()
        {
            $this->session->sess_destroy();
            redirect('/welcome', 'location');
        }
        
        public function postfb()
        {
            $all_userdata = $this->session->all_userdata();
            
            // dont have session security, redirect to first page
            if( !isset($all_userdata['session_id']) || !isset($all_userdata['login_success']) || !isset($all_userdata['usercode_id']) ) {        
                redirect('/welcome', 'location');
            }
            
            // user not yet saving info
            if( !isset($all_userdata['user_info']) ) {
                redirect('/user-info', 'location');
            }

            // connect FB
            $facebook = new Facebook(array(
                'appId'  => $this->config->item('appID'),
                'secret' => $this->config->item('appSecret'),
            )); //print_r($facebook);
            
            // check get FB user
            $user_id = $facebook->getUser();
            
            // user already login FB
            if($user_id) {
                // We have a user ID, so probably a logged in user.
                // If not, we'll get an exception, which we handle below.
                try {
                    $user_profile = $facebook->api('/me','GET');

                    // We have a user ID, so probably a logged in user.
                    // If not, we'll get an exception, which we handle below.
                    try {
                        // post link FB
                        $ret_obj = $facebook->api('/me/feed', 'POST', array('link' => $this->config->item('FB_share_link'),
                                                                            'name' => "santaclausiscalling.com",
                                                                            'image' => base_url().'public/img/fb_post_img.png',
                                                                            'message' => $user_profile['name']." đã tham gia SantaClausIsCalling và dành ngay 1 cơ hội được ông già Noel của ASUS tặng món quà giáng sinh tuyệt vời. Hãy đến ngay Booth của ASUS tại các thành phố để trải nghiệm Fonepad và dành những phần quà hấp dẫn",
                                                ));
                        // post link FB success
                        if(isset($ret_obj['id'])) { 
                            // set session post link FB id, FB id, FB name
                            $this->session->set_userdata('fb_link_id', $ret_obj['id']);
                            $this->session->set_userdata('fb_user_id', $user_id);
                            $this->session->set_userdata('fb_user_name', $user_profile['name']);
                            return 1;
                        }
                        // error post link, complete all 
                        else
                            redirect('/complete', 'location');
                        
                    } catch(FacebookApiException $e) {
                        // If the user is logged out, you can have a 
                        // user ID even though the access token is invalid.
                        // In this case, we'll get an exception, so we'll
                        // just ask the user to login again here.
                        $login_url = $facebook->getLoginUrl( array('scope' => 'publish_actions') ); 
                        // redirect to grand access to app
                        header('Location: '.$login_url);
                    } 
                } catch(FacebookApiException $e) {
                    // If the user is logged out, you can have a 
                    // user ID even though the access token is invalid.
                    // In this case, we'll get an exception, so we'll
                    // just ask the user to login again here.
                    $login_url = $facebook->getLoginUrl(); 
                    // redirect to login FB
                    header('Location: '.$login_url);                        
                }                  
            } 
            // user not yet login FB
            else {
                $login_url = $facebook->getLoginUrl();
                header('Location: '.$login_url);
            }                                       
        }
        
        public function share()
        {
            $all_userdata = $this->session->all_userdata();
            
            // dont have session security, redirect to first page
            if( !isset($all_userdata['session_id']) || !isset($all_userdata['login_success']) || !isset($all_userdata['usercode_id']) ) {        
                //redirect('/complete', 'location');
                echo 1;
            }
            
            // user not yet saving info
            if( !isset($all_userdata['user_info']) ) {
                //redirect('/complete', 'location');
                echo 2;
            }
            // current user have session user_info
            else {
                // check update user info
                if(!isset($all_userdata['update_user_info'])) {
                    //redirect('/user-info', 'location');
                    echo 3;
                }
                else {
                    // backup and destroy current share link id                    
                    $current_fb_link_id = '';
                    if(isset($all_userdata['fb_link_id'])) {
                        $current_fb_link_id = $all_userdata['fb_link_id'];
                        $this->session->unset_userdata('fb_link_id');
                    }                    
                    // post link FB
                    $this->postfb();
                    // get new all_userdata
                    $all_userdata = array();
                    $all_userdata = $this->session->all_userdata();
                    // check post link FB
                    // success
                    if(isset($all_userdata['fb_link_id'])) {
                        // get current FB share link id to usercode
                        $query = $this->db->query("SELECT fbpost_id FROM users_code WHERE id = ".$all_userdata['usercode_id']);
                        $query_row = $query->row_array();
                        $fbpost_id = ($query_row['fbpost_id']=='') ? array() : unserialize($query_row['fbpost_id']);
                        $fbpost_id[] = $all_userdata['fb_link_id'];
                        if($current_fb_link_id!='') {
                            $fbpost_id[] = $current_fb_link_id;
                        }
                        $fbpost_id = serialize($fbpost_id);
                        // update status =1 and link share id
                        $this->db->query("UPDATE users_code SET status = 1, fbpost_id = '".$fbpost_id."' WHERE id = ".$all_userdata['usercode_id']);
                        // update fb_name, fb_id
                        $fb_id = $all_userdata['fb_user_id'];
                        $fb_name = $all_userdata['fb_user_name'];
                        $this->db->query("UPDATE users SET fb_id = '$fb_id', fb_name = '".$fb_name."' WHERE id = ".$all_userdata['usercode_id']);
                        redirect('/complete', 'location');
                    }
                    // fail
                    else {
                        //redirect('/complete', 'location');
                        echo 4;
                    }
                }
            }   
        }               
        
        function generateRandomString($length = 9) {
            $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ9876541230';
            $charactersLength = strlen($characters);
            $randomString = '';
            for ($i = 0; $i < $length; $i++) {
                $randomString .= $characters[rand(0, $charactersLength - 1)];
            }
            return $randomString;
        }
        
        public function admin()
        {
            $data = array('action' => '');
			
			$all_userdata = $this->session->all_userdata();
            $data = array('action' => 'list_trung_thuong');
			
            // dont have admin session security, show login
            if( !isset($all_userdata['admin_key']) ) {
				$data['action'] = 'login';
				// check key
				if(isset($_POST) && isset($_POST['key'])) {
					$key = trim($_POST['key']);
					if($key === ADMIN_KEY) {
						$this->session->set_userdata('admin_key', 'pass');
					}
					redirect('/scic_admin','location');	
				}				
            }
			else {			
				$default_request = 1;
				// get request type
				$request_type = (isset($_GET['action'])) ? $_GET['action'] : $default_request;
				// process
				switch($request_type) {
					// show gift analytics
					case 1:	
						// define return type
                        $data['action'] = 'list_thong_ke';
						$start_time = START_DATE;
						// parse data		
						for($i=1; $i<=TOTAL_WEEK; $i++) {
							$end_time = $start_time + (86400*7)-1;
							// count gift
							$gift = array('ao' => 0, 'so' => 0, 'wish' => 0);
							$count_gift = $this->db->query("SELECT gift, COUNT(gift) as taken FROM users_gift WHERE gift <> 'code' AND createtime >= $start_time AND createtime <= $end_time GROUP BY gift");
							foreach($count_gift->result_array() as $row) {
								$gift[$row['gift']] = $row['taken'];
							}                                                    
							$week[$i] = array('start_time' => date('Y/m/d H:i:s', $start_time), 'end_time' => date('Y/m/d H:i:s', $end_time));
							$week[$i]['data'] = $gift;
							$start_time = $end_time+1;	
							$data['week'] = $week;
						}
						break;
					// show fonepad code list
					case 3:
						// define return type
                        $data['action'] = 'list_du_thuong';
						// define search
						$search = '';
						//if($_GET[''])
						break;
					// logout	
					case 4:
						$this->complete();
						break;
					// show user have gift list
					case 2:
					default:
						// define return type
                        $data['action'] = 'list_trung_thuong';
						break;
				}
			}
			$this->load->view('admin', $data);
		}

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */